package cn.kgc.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/11/15
 * 使用shiro框架完成认证操作
 */
public class ShiroAuthentication2 {

    public static void main(String[] args) {
        // 创建安全管理器
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        // 给安全管理器 设置realm  数据源  类似datasource 自定义realm
        MyRealm myRealm = new MyRealm();

        HashedCredentialsMatcher  hashedCredentialsMatcher =  new HashedCredentialsMatcher("md5");
        //密码加密的次数
        hashedCredentialsMatcher.setHashIterations(1024);


        // 设置密码匹配的规则 采用 MD5Hash
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        defaultSecurityManager.setRealm(myRealm);
        // 安全管理工具类 设置  安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        // 获取认证主体
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("admin", "12345");
        // 认证
        try {
            subject.login(usernamePasswordToken);
            //认证成功 封装json数据 返回前端

            // 授权
            if(subject.hasRole("admin")){
                System.out.println("管理员");


            }
            // 判定是否拥有所有的用户角色
            List<String> roles = Arrays.asList("admin", "aa");
            boolean b = subject.hasAllRoles(roles);
            System.out.println("b = " + b);

            boolean[] booleans = subject.hasRoles(roles);
            for (boolean aBoolean : booleans) {
                System.out.println("aBoolean = " + aBoolean);
            }


            // 根据权限字符串 完成权限认证  user:add   user:delete
            boolean permitted = subject.isPermitted("user:update");
            System.out.println("permitted = " + permitted);

        } catch (UnknownAccountException e) {
            System.out.println("用户名不存在");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }

        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated = " + authenticated);



    }
}
